package com.yygo.util;

import com.yygo.configentity.attachment.Role;
import com.yygo.configentity.attachment.RoleAttachment;
import com.yygo.configentity.attachment.RoleAttachments;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by huanli on 2015/11/12.
 */
public class RoleAttachmentConfigUtil {
    private static Log log = LogFactory.getLog(RoleAttachmentConfigUtil.class);
    public RoleAttachments read(){
        RoleAttachments roleAttachments = new RoleAttachments();
        SAXReader saxReader= new SAXReader();
        Document document = null;
        try{
            URL xmlPath = this.getClass().getClassLoader().getResource("RoleAttachment.xml");
            document = saxReader.read(xmlPath);
            Element root = document.getRootElement();
            List<Element> childList = root.elements();
            List<Role> roles = new ArrayList<>();
            for (Element childNode:childList) {
                Role role = new Role();
                String name = childNode.valueOf("@name" );
                role.setName(name);
                List<RoleAttachment> roleAttachmentList = new ArrayList<>();
                for(Object properties: childNode.elements("Attachments")) {
                    RoleAttachment roleAttachment = new RoleAttachment();
                    String status = ((Node) properties).valueOf("@status");
                    String phases = ((Node) properties).valueOf("@phases");
                    String attachmentKey = ((Node) properties).getText().replace("\n", "").replace(" ", "");
                    boolean allPhase = ((Node) properties).valueOf("@allPhase").equals("true")? true:false;
                    String type = ((Node) properties).valueOf("@type");
                    roleAttachment.setPhases(phases.split(","));
                    roleAttachment.setAllPhase(allPhase);
                    roleAttachment.setStatus(status);
                    roleAttachment.setAttachmentKey(attachmentKey);
                    roleAttachment.setType(type);
                    roleAttachmentList.add(roleAttachment);
                }
                role.setRoleAttachments(roleAttachmentList);
                roles.add(role);
            }
            roleAttachments.setRoles(roles);
        }
        catch(Exception e){
            log.trace(e.getMessage());
        }
        return roleAttachments;
    }
}
